package com.example.democlient;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.democlient.network.SocketService;
import com.example.democlient.network.serverpackets.SM_TASK_DELETE_REQUEST;
import com.example.democlient.network.serverpackets.SM_TASK_PAUSE_REQUEST;
import com.example.democlient.network.serverpackets.SM_TASK_QUERY_RD_REQUEST;
import com.example.democlient.network.serverpackets.SM_TASK_QUERY_REQUEST;

@SuppressLint("HandlerLeak")
public class TaskListActivity extends ListActivity implements OnClickListener{

	Button newBtn;
	int removeTaskId;
	private MyApplication app;
	
	Handler mainHandler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {
	        switch (msg.what) {  
	        	case 0: 
	        		Toast.makeText(MyApplication.mDemoApp.getApplicationContext(), "获取数据错误.",Toast.LENGTH_LONG).show();
	        	break;
	        	case 1:
	        		getListView().setAdapter(new MyAdapter());
	        	break;
	        	case 2:
	        		SocketService.getInstance().sendPacket(new SM_TASK_QUERY_REQUEST(app.account), app);
	        	break;
	        	case 3:
	        		SocketService.getInstance().sendPacket(new SM_TASK_QUERY_REQUEST(app.account), app);
	        	break;
	        }  
        }
    };  

	 @Override
	 protected void onCreate(Bundle savedInstanceState) {
	      super.onCreate(savedInstanceState);
	      this.requestWindowFeature(Window.FEATURE_NO_TITLE);
	      this.setContentView(R.layout.activity_task_list);
	      app = (MyApplication)this.getApplication();
	      app.addActivity(this);
		  app.setHandler(this.getClass(),mainHandler);
	      newBtn = (Button)findViewById(R.id.newBtn);
	      newBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
		        Intent intent = new Intent();
		        intent.setClass(TaskListActivity.this, TaskCreateActivity.class);
		        startActivity(intent);
			}
		  });
//	      LinearLayout topLayout = (LinearLayout)this.findViewById(R.id.topLayout);
//	      topLayout.getBackground().setAlpha(0);
//	      LinearLayout buttonLayout = (LinearLayout)this.findViewById(R.id.bottomLayout);
//	      buttonLayout.getBackground().setAlpha(0);
	 }
	 
	 @Override
	public void onStart(){
		super.onStart();
		SocketService.getInstance().sendPacket(new SM_TASK_QUERY_REQUEST(app.account), app);
	}
	 
	@Override
	protected void onResume() {
		app.flag = 0;
		super.onResume();
	}
	 
	 protected void onListItemClick(ListView l, View v, int position, long id) {  
			super.onListItemClick(l, v, position, id);  
//          Toast.makeText(TaskListActivity.this, "You click: " + position, Toast.LENGTH_SHORT).show();  
//			Task task = app.taskList.get(position);
//	    	String tempValue = task.getId()+"#"+task.getFlag()+"#"+task.getAreaName()+"#"+task.getAddressStr()+"#"+task.getTelephone()+"#"+
//	    	task.getRemark()+"#"+task.getAddressId()+"#"+task.getXaxis()+"#"+task.getYaxis();
	    	Intent toIntent = new Intent();
	 		toIntent.setClass(TaskListActivity.this,TaskCreateActivity.class);
	 		toIntent.putExtra("content", position);
			startActivity(toIntent);
	    }
	@Override
	public void onClick(View v) {
		switch(v.getId()){

		}
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item){
    	super.onOptionsItemSelected(item);
    	if(item.getItemId()==R.id.menu_settings){
    		app.exit();
    	}
		return true;
    }
    
	 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	        super.onActivityResult(requestCode, resultCode, data);
	         if (requestCode == 0 && resultCode == RESULT_OK) {
	        }
	 }
	  
	  public class MyAdapter extends BaseAdapter{
	        public int getCount() {
	           return app.taskList.size();
	        }
	 
	        public Object getItem(int position) {
	            return app.taskList.get(position);
	        }
	 
	        public long getItemId(int position) {
	            return position;
	        }
	 
	 
	        public View getView(int position, View convertView, ViewGroup parent) {
	            LayoutInflater inflater = TaskListActivity.this.getLayoutInflater();
	             final View view = inflater.inflate(R.layout.activity_task_list_item, null);
	             final TextView taskFlag = (TextView) view.findViewById(R.id.taskFlag);
	             taskFlag.setText(app.taskList.get(position).getFlag()==1?"收":"派");
	             final TextView inputDate = (TextView)view.findViewById(R.id.inputDate);
	             inputDate.setText(app.taskList.get(position).getCreateDate());
	             final TextView phoneNum = (TextView)view.findViewById(R.id.telephoneNum);
	             phoneNum.setText(app.taskList.get(position).getTelephone());
	             final TextView address = (TextView)view.findViewById(R.id.address);
	             address.setText(app.taskList.get(position).getAddressStr());
	             final TextView remarkContent = (TextView)view.findViewById(R.id.remarkContent);
	             remarkContent.setText(app.taskList.get(position).getRemark());
	             final ImageView callBtn = (ImageView) view.findViewById(R.id.telCallBtn);
	             callBtn.setOnClickListener(new OnClickListener(){
					@Override
					public void onClick(View v) {
						  AlertDialog.Builder builder = new Builder(TaskListActivity.this);
						  builder.setMessage("确定要拨号吗？");
						  builder.setTitle("提示");
						  builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
							   @Override
							   public void onClick(DialogInterface dialog, int which) {
							    dialog.dismiss();
							    String strMobile = phoneNum.getText().toString();
							    Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+strMobile));
							    TaskListActivity.this.startActivity(intent);
							  }
						  });
						  builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
							   @Override
							   public void onClick(DialogInterface dialog, int which) {
							    dialog.dismiss();
							   }
						  });
						  builder.create().show();
					}
	             });
	             
	             final ImageView startBtn = (ImageView) view.findViewById(R.id.taskStartBtn);
	             final byte pauseFlag = app.taskList.get(position).getPauseFlag();
	             final int taskId = app.taskList.get(position).getId();
	             if(pauseFlag==0){
	            	 startBtn.setBackgroundDrawable(TaskListActivity.this.getResources().getDrawable(R.drawable.task_start));
	             }else{
	            	 startBtn.setBackgroundDrawable(TaskListActivity.this.getResources().getDrawable(R.drawable.task_pause));
	             }
	             startBtn.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if(pauseFlag==0){
							 startBtn.setBackgroundDrawable(TaskListActivity.this.getResources().getDrawable(R.drawable.task_pause));
							 if(SocketService.getInstance().sendPacket(new SM_TASK_PAUSE_REQUEST(taskId,1), app)){
									
							 }
						}else{
							 startBtn.setBackgroundDrawable(TaskListActivity.this.getResources().getDrawable(R.drawable.task_start));
							 if(SocketService.getInstance().sendPacket(new SM_TASK_PAUSE_REQUEST(taskId,0), app)){
									
							 }
						}
					}
                });
	             
	             
             ImageView taskDeleteBtn = (ImageView)view.findViewById(R.id.taskDeleteBtn);
             taskDeleteBtn.setTag( position);
             taskDeleteBtn.setOnClickListener(new OnClickListener(){
             public void onClick(View v) {
                	 int position = Integer.parseInt(v.getTag().toString());
                	 TaskListActivity.this.removeTaskId = position;
					 if(SocketService.getInstance().sendPacket(new SM_TASK_DELETE_REQUEST(taskId), app)){
					 }
             }});
	              
	         return view;
	        }
	         
	    }
}
